package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或更新地理位置
    public void save(Long userId, Double lat, Double lon, String addrStr) {
        //1.查询当前用户的位置信息是否存在
        Query query = Query.query(Criteria.where("userId").is(userId));
        boolean exists = mongoTemplate.exists(query, UserLocation.class);
        if (!exists) {
            //2.如果不存在，保存
            UserLocation location = new UserLocation();
            location.setUserId(userId);
            location.setAddress(addrStr);
            location.setCreated(System.currentTimeMillis());
            GeoJsonPoint point = new GeoJsonPoint(lon, lat);
            location.setLocation(point);
            mongoTemplate.save(location);
        } else {
            //3.如果信息存在，更新
            Update update = new Update();
            //条件，设置字段最新的数据
            update.set("location", new GeoJsonPoint(lon, lat));
            update.set("address", addrStr);
            update.set("updated", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }

    }

    //查询附近的人
    public List<Long> searchNear(Long userId, String miles) {
        //查询当前用的地理位置数据
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation ul = mongoTemplate.findOne(query, UserLocation.class);
        //1.查找圆点（圆心）--当前用户位置
        GeoJsonPoint location = ul.getLocation();
        //2.绘制半径
        Distance distance = new Distance(Double.valueOf(miles)/1000, Metrics.KILOMETERS);//距离，单位
        //3.绘制圆（圆点+半径
        Circle circle = new Circle(location,distance);
        //4.在已有的位置数据中，查询圆所覆盖的所有点
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);//坐标点，是否在圆内部
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        //5.返回附近的id
        return CollUtil.getFieldValues(list,"userId",Long.class);
    }
}
